//导出记录弹窗
import { useState, useEffect } from 'react';
import { Popconfirm, Button, message } from 'antd';
import moment from 'moment';
import CommonTable from '@/components/CommonTable';
import CommonLoading from '@/components/CommonLoading';
import CommonModal from '@/components/CommonModal';
import { getDifferUserDetails } from '@/utils/authority';
import { httpChange, GetChinese } from '@/utils/utils.jsx';
import {
  getTableListOp,
  deleteExportTask,
  downLoadFileOp,
} from '@/pages/BasicModule/taskCenter/service';

const taskStateMap = {
  0: '待执行',
  1: '执行中',
  2: '已完成',
  3: '执行失败',
};

const exportTypeMap = {
  1: '订单导出',
  2: '商品导出',
  3: '账单导出',
  4: '账期导出',
  5: '库存导出',
  6: '采购单导出',
  7: '售后导出',
  8: '报表导出',
  9: '售后导出',
};

const ExportRecordModal = ({ visible, handleCancel }) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]); //表格数据

  useEffect(() => {
    if (visible) {
      getCurrentUserExportRecord();
    }
  }, [visible]);

  //获取当前账号当天操作导出
  const getCurrentUserExportRecord = async () => {
    setLoading(true);
    const { success, data } = await getTableListOp({
      startTime: moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
      endTime: moment().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
      userId: (getDifferUserDetails() || {}).id,
      current: 1,
      size: 1000,
    });
    if (success) {
      const { records = [] } = data;
      setData(records);
    }
    setLoading(false);
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      fixed: 'left',
      width: 60,
      render: (t, r, i) => i + 1,
    },
    {
      title: '任务类型',
      dataIndex: 'exportType',
      key: 'exportType',
      width: 90,
      render: (text) => exportTypeMap[text],
    },
    {
      title: '文件名称',
      dataIndex: 'fileName',
      key: 'fileName',
      width: 100,
    },
    {
      title: '任务状态',
      dataIndex: 'state',
      key: 'state',
      width: 90,
      render: (text) => (
        <span className={text == 3 ? 'common-color9' : ''}>
          {taskStateMap[text]}
        </span>
      ),
    },
    {
      title: '失败原因',
      dataIndex: 'errorMsg',
      key: 'errorMsg',
      width: 150,
      render: (text) => text || '-',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
    },
    {
      title: '下载次数',
      dataIndex: 'downloadNum',
      key: 'downloadNum',
      align: 'center',
      width: 80,
    },
    {
      title: '操作',
      dataIndex: 'opeartor',
      key: 'opeartor',
      align: 'center',
      fixed: 'right',
      width: 90,
      render: (text, record) => {
        if (record.state === 0 || record.state === 1) {
          return (
            <Popconfirm
              title="确定要删除吗?"
              onConfirm={() => deleteFunc(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <span className="common-color2">删除</span>
            </Popconfirm>
          );
        } else if (record.state === 2) {
          return (
            <span
              className="common-color2"
              onClick={() => handleClickExport(record.id)}
            >
              下载文件
            </span>
          );
        } else {
          return '无';
        }
      },
    },
  ];

  const deleteFunc = async (ids) => {
    setLoading(true);
    const { data, success } = await deleteExportTask({ ids });
    if (success) {
      message.success(data);
      getCurrentUserExportRecord();
    }
    setLoading(false);
  };

  //导出文件
  const exportFile = (url) => {
    fetch(httpChange(url), {
      method: 'GET',
    })
      .then((res) => res.blob())
      .then((data) => {
        const blobUrl = window.URL.createObjectURL(data);
        const a = document.createElement('a');
        a.download = GetChinese(url) + '.xlsx';
        a.href = httpChange(blobUrl);
        a.click();
      });
  };

  const handleClickExport = async (id) => {
    setLoading(true);
    const { data, success } = await downLoadFileOp({ id });
    if (success) {
      message.success('浏览器下载中，请稍后');
      exportFile(data);
      getCurrentUserExportRecord();
    }
    setLoading(false);
  };

  // table的props
  const tableProps = {
    data,
    columns,
    rowKey: 'id',
    scroll: { y: 500 },
  };

  return (
    <>
      <CommonModal
        title="导出记录"
        visible={visible}
        onCancel={handleCancel}
        width="880px"
        footer={[
          <Button key="cancel" onClick={handleCancel}>
            关闭
          </Button>,
        ]}
      >
        <p style={{ marginBottom: '16px' }}>
          显示当前子账号当天的表格导出记录，往日记录可以去基础管理——任务中心查看
        </p>
        <CommonTable {...tableProps} />
        <CommonLoading loading={loading} />
      </CommonModal>
    </>
  );
};

export default ExportRecordModal;
